package com.lagou.parse;

import com.lagou.config.Configuration;
import com.lagou.config.MapperStatement;
import com.mysql.jdbc.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by seemygo on 2020/11/13.
 */
public class SqlConfigBuilder {
    private Configuration configuration;

    public SqlConfigBuilder(Configuration configuration) {
        this.configuration = configuration;
    }


    public Configuration parseSqlConfig(InputStream inputStream) throws Exception {
        //解析字节输入流   将sqlMapper.xml信息配置到configuration的mapperStatementMap中
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //针对查询进行解析
        List<Element> elementList = rootElement.selectNodes("select");
        configuration = parseSqlSign(elementList, namespace);
        //对插入的解析
        List<Element> insertElementList = rootElement.selectNodes("insert");
        configuration =parseSqlSign(insertElementList,namespace);
        //对修改的解析
        List<Element> updateElementList = rootElement.selectNodes("update");
        configuration =parseSqlSign(updateElementList,namespace);
        //对删除的解析
        List<Element> deleteElementList = rootElement.selectNodes("delete");
        configuration =parseSqlSign(deleteElementList,namespace);


        return this.configuration;
    }

    private Configuration parseSqlSign(List<Element> elementList,String namespace) throws Exception {
        for (Element element : elementList) {
            MapperStatement mapperStatement=new MapperStatement();
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            String namespaceId=namespace+"."+id;
            if(!StringUtils.isNullOrEmpty(resultType)){
                Class<?> resultTypeClass=getClassType(resultType);
                mapperStatement.setResultType(resultTypeClass);
            }
            if(!StringUtils.isNullOrEmpty(parameterType)){
                Class<?> parameterTypeClass=getClassType(parameterType);
                mapperStatement.setParameterType(parameterTypeClass);
            }
            mapperStatement.setId(id);
            mapperStatement.setSql(sql);
            configuration.getMapperStatementMap().put(namespaceId,mapperStatement);
        }
        return configuration;
    }

    private Class<?> getClassType(String type) throws ClassNotFoundException {
        Class<?> classType = Class.forName(type);
        return  classType;
    }
}
